package com.engine.ld.utils;

import com.weaver.general.BaseBean;
import org.dom4j.Element;
import weaver.conn.RecordSet;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ZhangLei
 * @date 2021/7/28
 * 包括主表、明细表对应的xml解析、主表插入、明细表插入
 */
public class ReadXmlInsert {
    private final static BaseBean bb = new BaseBean();

    /*
     * 获取正确的xml
     * */
    public static String getRealXml(String xml) {
        if (!xml.contains("<_--5CTYPE_--3DSTRING>")) {
            return xml;
        }
        int start = xml.indexOf("<_--5CTYPE_--3DSTRING>") + "<_--5CTYPE_--3DSTRING>".length();
        int end = xml.indexOf("</_--5CTYPE_--3DSTRING>");
        return xml.substring(start, end).trim();
    }

    /**
     * 解析主表xml方法
     *
     * @param root：xml根节点
     * @param mainName：主表在xml中对应的节点名 出参：含解析xml结果的List集合
     */
    public static Map<String, String> dealMain(Element root, String mainName, String[] mainparams) {
//        按照元素的标签名获得对应的节点集合
//        主表解析结果Map<String, Object> headResult
        Map<String, String> headResult = new HashMap<>();

        List<Element> head1 = root.elements(mainName);
        for (Element elementHead : head1) {
            for (String mainParam : mainparams) {
                headResult.put(mainParam.toLowerCase(), elementHead.elementTextTrim(mainParam));
            }
        }
        return headResult;
    }

    /**
     * 解析明细表的方法
     *
     * @param root：xml根节点
     * @param dtName：明细表在xml中对应的节点名
     */
    public static List<Map<String, Object>> dealDt(Element root, String dtName, String[] dtparams) {
        //        明细表解析结果List<Map<String, Object>> itemResult
        List<String> collect = new ArrayList<>();
        List<Element> item = root.elements(dtName);
        Integer listNum = 0;
        for (Element elementItem : item) {
            for (String dtParam : dtparams) {
                List<Element> miniList = elementItem.elements(dtParam);
                listNum = miniList.size();//一共需要分listNum个组（说明行项目中传递了listNum组数据）
                for (Element element : miniList) {
//                获取节点名和对应节点值
                    collect.add(element.getName() + "=" + element.getData());
                }
            }
        }
        System.out.println("collect:" + collect);


        List<Map<String, Object>> itemResult = doItem(collect, listNum);
//        System.out.println("itemResult:" + itemResult);
        return itemResult;
    }

    /**
     * @param collect：解析item节点后结果
     * @param listNum：所需分组数
     */
    public static List<Map<String, Object>> doItem(List<String> collect, int listNum) {
        List<Map<String, Object>> itemResult = new ArrayList<>();
        Map<String, Object> map0 = new HashMap<>();
        Map<String, Object> map1 = new HashMap<>();
        Map<String, Object> map2 = new HashMap<>();
        Map<String, Object> map3 = new HashMap<>();
        Map<String, Object> map4 = new HashMap<>();
        Map<String, Object> map5 = new HashMap<>();
        Map<String, Object> map6 = new HashMap<>();
        Map<String, Object> map7 = new HashMap<>();
        Map<String, Object> map8 = new HashMap<>();
        Map<String, Object> map9 = new HashMap<>();


        for (int i = 0; i < collect.size(); i++) {
            String keyValue = collect.get(i);
            String key = keyValue.substring(0, keyValue.indexOf("=")).toLowerCase();
            String value = keyValue.substring(key.length() + 1);
            if (i % listNum == 0) {
                map0.put(key, value);
            } else if (i % listNum == 1) {
                map1.put(key, value);
            } else if (i % listNum == 2) {
                map2.put(key, value);
            } else if (i % listNum == 3) {
                map3.put(key, value);
            } else if (i % listNum == 4) {
                map4.put(key, value);
            } else if (i % listNum == 5) {
                map5.put(key, value);
            } else if (i % listNum == 6) {
                map6.put(key, value);
            } else if (i % listNum == 7) {
                map7.put(key, value);
            } else if (i % listNum == 8) {
                map8.put(key, value);
            } else if (i % listNum == 9) {
                map9.put(key, value);
            }
        }

        if (!map0.isEmpty()) {
            itemResult.add(map0);
        }
        if (!map1.isEmpty()) {
            itemResult.add(map1);
        }
        if (!map2.isEmpty()) {
            itemResult.add(map2);
        }
        if (!map3.isEmpty()) {
            itemResult.add(map3);
        }
        if (!map4.isEmpty()) {
            itemResult.add(map4);
        }
        if (!map5.isEmpty()) {
            itemResult.add(map5);
        }
        if (!map6.isEmpty()) {
            itemResult.add(map6);
        }
        if (!map7.isEmpty()) {
            itemResult.add(map7);
        }
        if (!map8.isEmpty()) {
            itemResult.add(map8);
        }
        if (!map9.isEmpty()) {
            itemResult.add(map9);
        }
        return itemResult;
    }

    /**
     * 向主表中添加数据
     * @param mainResult：主表的键值对集合
     * @param tableName:需要操作的表对象名
     * @param mainparams:主表的字段名数组
     * @return insertID 插入记录的id值
     * */
    public static String insertMain(Map<String, String> mainResult,String tableName,String[] mainparams){
        String insertId = "";
        String sql = "insert into "+ tableName + " (";
        for (int i = 0; i < mainparams.length; i++) {
            if (i!=mainparams.length-1){
                sql += mainparams[i].toLowerCase()+",";
            }else {
                sql += mainparams[i].toLowerCase()+")";
            }
        }
        sql += " values (";
        for (int i = 0; i < mainparams.length; i++) {
            if (i!=mainparams.length-1){
                sql += mainResult.get(mainparams[i].toLowerCase())+",";
            }else {
                sql += mainResult.get(mainparams[i].toLowerCase())+")";
            }
        }
//        向主表中插入数据
        RecordSet mainRS = new RecordSet();
//        如果成功，获取刚刚插入记录的id
        if (mainRS.executeQuery(sql)){
            bb.writeLog("数据插入成功，开始获取记录的id值");
            String getIdSql = "select id from "+tableName+" where ";
            for (int i = 0; i < mainparams.length; i++) {
                if (i!=mainparams.length-1){
                    getIdSql += mainparams[i].toLowerCase()+"="+mainResult.get(mainparams[i].toLowerCase())+" and ";
                }else {
                    getIdSql += mainparams[i].toLowerCase()+"="+mainResult.get(mainparams[i].toLowerCase());
                }
            }
            RecordSet getIdRS = new RecordSet();
            if (getIdRS.executeQuery(getIdSql)){
                insertId = getIdRS.getString("id");
            }
        }else {
            bb.writeLog("数据插入失败");
        }
        return insertId;
    }

    /**
     *向明细表中添加数据
     * @param dtResult 明细表的键值对数组
     * @param tableName 明细表名
     * @param dtparams 明细表字段名
     * @param id 对应的主表id
     * */
    public static int insertDt(List<Map<String, Object>> dtResult,String tableName,String[] dtparams,String id){
        int insertResult = 0;
        int insertNum = dtResult.size();
        for (int i = 0; i < insertNum; i++) {
            Map<String,Object> needInsertMap = dtResult.get(i);
            String insertDtSql = "";
            insertDtSql += "insert into "+tableName+" (mainid,";
            for (int ii = 0; ii < dtparams.length; ii++) {
                if (ii!=dtparams.length-1){
                    insertDtSql += dtparams[ii].toLowerCase()+",";
                }else {
                    insertDtSql += dtparams[ii].toLowerCase()+")";
                }
            }
            insertDtSql += " values ("+id+",";
            for (int iii = 0; iii < dtparams.length; iii++) {
                if (iii!=dtparams.length-1){
                    insertDtSql += needInsertMap.get(dtparams[iii].toLowerCase())+",";
                }else {
                    insertDtSql += needInsertMap.get(dtparams[iii].toLowerCase())+")";
                }
            }

            RecordSet dtRs = new RecordSet();
            if (dtRs.executeQuery(insertDtSql)){
                bb.writeLog("明细表记录"+i+"插入成功");
                insertResult += 1;
            }else {
                bb.writeLog("明细表记录"+i+"插入失败，插入语句是："+insertDtSql);
                insertResult = insertResult-1000;
            }
        }
        return insertResult;
    }
}
